package services

import (
	"fmt"
	"log"
	"os"
	"path/filepath"
	"sync"
	"time"
)

// ANSI 颜色码
const (
	colorReset  = "\033[0m"
	colorRed    = "\033[31m"
	colorGreen  = "\033[32m"
	colorYellow = "\033[33m"
	colorBlue   = "\033[34m"
	colorPurple = "\033[35m"
	colorCyan   = "\033[36m"
	colorGray   = "\033[37m"
)

var (
	infoLogger *log.Logger
	logFile    *os.File
	logMutex   sync.Mutex
)

// 为日志添加颜色
func colorize(color, message string) string {
	// 检查是否在终端环境中
	if fileInfo, _ := os.Stdout.Stat(); (fileInfo.Mode() & os.ModeCharDevice) != 0 {
		return color + message + colorReset
	}
	return message
}

// InitLogger 初始化日志服务
func InitLogger() error {
	// 创建logs目录（如果不存在）
	if err := os.MkdirAll("logs", 0755); err != nil {
		return fmt.Errorf("创建日志目录失败: %v", err)
	}

	// 打开日志文件
	logPath := filepath.Join("logs", "info.log")
	file, err := os.OpenFile(logPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
	if err != nil {
		return fmt.Errorf("打开日志文件失败: %v", err)
	}

	logFile = file
	infoLogger = log.New(file, "", log.Ldate|log.Ltime)
	return nil
}

// 添加关闭方法
func CloseLogger() {
	if logFile != nil {
		logFile.Sync()
		logFile.Close()
	}
}

// LogInfo 记录信息日志
func LogInfo(format string, v ...interface{}) {
	logMutex.Lock()
	defer logMutex.Unlock()

	message := fmt.Sprintf(format, v...)
	if infoLogger != nil {
		infoLogger.Println("[INFO] " + message)
	}
	log.Println(colorize(colorGreen, "[INFO] ") + message)
}

// LogError 记录错误日志
func LogError(format string, v ...interface{}) {
	logMutex.Lock()
	defer logMutex.Unlock()

	message := fmt.Sprintf(format, v...)
	if infoLogger != nil {
		infoLogger.Println("[ERROR] " + message)
	}
	log.Println(colorize(colorRed, "[ERROR] ") + message)
}

// LogWarn 记录警告日志
func LogWarn(format string, v ...interface{}) {
	logMutex.Lock()
	defer logMutex.Unlock()

	message := fmt.Sprintf(format, v...)
	if infoLogger != nil {
		infoLogger.Println("[WARN] " + message)
	}
	log.Println(colorize(colorYellow, "[WARN] ") + message)
}

// LogDebug 记录调试日志
func LogDebug(format string, v ...interface{}) {
	logMutex.Lock()
	defer logMutex.Unlock()

	message := fmt.Sprintf(format, v...)
	if infoLogger != nil {
		infoLogger.Println("[DEBUG] " + message)
	}
	log.Println(colorize(colorCyan, "[DEBUG] ") + message)
}

// RequestTimer 返回一个计时函数，调用该函数时返回从创建到调用经过的时间
func RequestTimer() func() time.Duration {
	start := time.Now()
	return func() time.Duration {
		return time.Since(start)
	}
}

// LogRequest 记录请求信息
func LogRequest(method, path, ip string, statusCode int, duration time.Duration) {
	// 根据状态码选择颜色
	var statusColor string
	switch {
	case statusCode >= 500:
		statusColor = colorRed
	case statusCode >= 400:
		statusColor = colorYellow
	case statusCode >= 300:
		statusColor = colorCyan
	default:
		statusColor = colorGreen
	}

	message := fmt.Sprintf(
		"%s %s | IP: %s | Status: %s%d%s | Duration: %v",
		colorize(colorBlue, method),
		colorize(colorPurple, path),
		colorize(colorGray, ip),
		statusColor,
		statusCode,
		colorReset,
		duration,
	)
	LogInfo(message)
}
